package com.internetCafes.spms.web.certificate.controller;

import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.module.excel.ExcelUtils;
import com.internetCafes.spms.common.module.excel.po.CertificateRenewalInfoExcelPro;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.model.pageModel.DataGrid;
import com.internetCafes.spms.core.utils.Query;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.web.certificate.entity.CertificateInfo;
import com.internetCafes.spms.web.certificate.entity.CertificateRenewalInfo;
import com.internetCafes.spms.web.certificate.service.CertificateInfoService;
import com.internetCafes.spms.web.certificate.service.CertificateRenewalInfoService;
import com.internetCafes.spms.web.certificate.vo.CertificateInfoVo;
import com.internetCafes.spms.web.certificate.vo.CertificateRenewalInfoVo;
import com.internetCafes.spms.web.sys.model.ResourceInfo;
import com.internetCafes.spms.web.sys.service.ResourceInfoService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 证书延期信息
 *
 * @author Sunny
 * @email rekeeper2011@hotmail.com
 * @date 2019-10-31 18:10:59
 */
@RestController
@RequestMapping("/certificate/certificateRenewalInfo")
public class CertificateRenewalInfoController {

    @Autowired
    private CertificateRenewalInfoService certificateRenewalInfoService;

    @Autowired
    private CertificateInfoService certificateInfoService;

    @Autowired
    private ResourceInfoService resourceInfoService;

    /**
     * 批量导出
     */
    @RequestMapping("/export")
    @RequiresPermissions("certificate:certificateRenewalInfo:list")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        params.put("warn", com.internetCafes.spms.core.utils.DateUtils.getBeAfMonth(3));
        params.put("statuses", CommonConstants.CertificateStatus.EXCEPT_DELETE);
        List<CertificateInfoVo> certificateInfoVos = certificateInfoService.selectByJobParams(params);

        List<CertificateRenewalInfoExcelPro> certificateRenewalInfoExcelPros = certificateInfoVos.stream()
                .map(certificateInfoVo -> {
                    CertificateRenewalInfoExcelPro certPro = new CertificateRenewalInfoExcelPro();

                    BeanUtils.copyProperties(certificateInfoVo, certPro);
                    certPro.setStatus(certificateInfoVo.getWarning() ? "快到期" :
                            (certificateInfoVo.getDisable() ? "已逾期" : "未到期"));

                    return certPro;
                }).collect(Collectors.toList());

        ExcelUtils.exportExcel(certificateRenewalInfoExcelPros, "证书延期信息", "证书延期信息", CertificateRenewalInfoExcelPro.class, "证书延期信息.xls", response);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("certificate:certificateRenewalInfo:list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String orderBy = request.getParameter("orderBy");
        if (StringUtils.isNotBlank(orderBy)) {
            params.put("orderBy", com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(orderBy));
        }
        //查询列表数据
        Query query = new Query(params);

        DataGrid dataGrid = certificateRenewalInfoService.dataGrid(params, query.getPage(), query.getLimit());

        return R.ok().put("page", dataGrid);
    }


    /**
     * 列表
     */
    @RequestMapping("/getRenewals")
    @RequiresPermissions("certificate:certificateRenewalInfo:list")
    public R getTransactions(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        List<CertificateInfoVo> certificateInfoVoList = certificateInfoService.selectByJobParams(params);
        CertificateInfoVo c = null;
        if (CollectionUtils.isNotEmpty(certificateInfoVoList)) {
            c = certificateInfoVoList.get(0);
            params = new HashMap<>();
            params.put("moduleId", c.getId());
            params.put("moduleCode", CommonConstants.ResourceInfo_PIC_Certi);
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(params);
            if (CollectionUtils.isNotEmpty(resourceInfoList)) {
                c.setCertifInfoList(resourceInfoList);
            }

            params.put("moduleCode", CommonConstants.ResourceInfo_PIC_Constrat);
            resourceInfoList = resourceInfoService.query(params);
            if (CollectionUtils.isNotEmpty(resourceInfoList)) {
                c.setContractInfoList(resourceInfoList);
            }
        }

        params = new HashMap<>();
        params.put("certificateId", id);
        List<CertificateRenewalInfo> certificateRenewalInfoList = certificateRenewalInfoService.query(params);
        List<CertificateRenewalInfoVo> certificateRenewalInfoVos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(certificateRenewalInfoList)) {
            certificateRenewalInfoList.forEach((r) -> {
                CertificateRenewalInfoVo vo = new CertificateRenewalInfoVo();
                BeanUtils.copyProperties(r, vo);
                Map<String, Object> _params = new HashMap<>();
                _params.put("moduleId", r.getId());
                _params.put("moduleCode", CommonConstants.ResourceInfo_PIC_CertificateRenewalInfo);
                List<ResourceInfo> resourceInfoList = resourceInfoService.query(_params);
                if (CollectionUtils.isNotEmpty(resourceInfoList)) {
                    vo.setContractInfoList(resourceInfoList);
                }
                certificateRenewalInfoVos.add(vo);
            });
        }
        return R.ok().put("c", c).put("ctList", certificateRenewalInfoVos);
    }


    /**
     * 保存
     */
    @SysLog("保存人员证书延期记录")
    @RequestMapping("/save")
    @RequiresPermissions("certificate:certificateRenewalInfo:save")
    public R save(@RequestBody CertificateRenewalInfoVo certificateRenewalInfo) {

        if (certificateRenewalInfo.getCertificateId() != null) {
            CertificateInfo c = certificateInfoService.findById(certificateRenewalInfo.getCertificateId());
            Integer num = (c.getRenewalNum() == null ? 0 : c.getRenewalNum()) + 1;
            c.setRenewalNum(num);
            c.setRenewalTime(certificateRenewalInfo.getRenewalTime());
            c.setValidityEndTime(certificateRenewalInfo.getValidityEndTime());
            certificateInfoService.update(c);

            CertificateRenewalInfo cr = new CertificateRenewalInfo(certificateRenewalInfo.getTenantId(), certificateRenewalInfo.getCertificateId(), certificateRenewalInfo.getRenewalTime(), certificateRenewalInfo.getValidityStartTime(), certificateRenewalInfo.getValidityEndTime(), certificateRenewalInfo.getRemark());
            cr.setCreateBy(ShiroUtils.getUserId());
            cr.setRenewalFee(certificateRenewalInfo.getRenewalFee());
            certificateRenewalInfoService.save(cr);
            saveResourceInfo(certificateRenewalInfo, cr);
        }
        return R.ok();
    }


    /**
     * 修改
     */
    @SysLog("修改人员证书延期记录")
    @RequestMapping("/update")
    @RequiresPermissions("certificate:certificateRenewalInfo:update")
    public R update(@RequestBody CertificateRenewalInfoVo certificateRenewalInfo) {
        CertificateInfo c = certificateInfoService.findById(certificateRenewalInfo.getCertificateId());
        c.setRenewalTime(certificateRenewalInfo.getRenewalTime());
        c.setValidityEndTime(certificateRenewalInfo.getValidityEndTime());
        certificateInfoService.update(c);
        certificateRenewalInfoService.update(certificateRenewalInfo);
        return R.ok();
    }


    /**
     * 保存资源信息
     *
     * @param vo
     * @param c
     */
    private void saveResourceInfo(CertificateRenewalInfoVo vo, CertificateRenewalInfo c) {
        if (StringUtils.isNotBlank(vo.getContractPic()) && vo.getContractPic().split(",").length > 0) {
            String[] certiPics = vo.getContractPic().split(",");
            for (String certiPic : certiPics) {
                ResourceInfo r = new ResourceInfo(ShiroUtils.getUserId(), CommonConstants.ResourceInfo_PIC_CertificateRenewalInfo, c.getId(), "pic" + File.separator + certiPic);
                resourceInfoService.save(r);
            }
        }
    }


    /**
     * 删除
     */
    @SysLog("删除人员证书延期记录")
    @RequestMapping("/delete")
    @RequiresPermissions("certificate:certificateRenewalInfo:delete")
    public R delete(@RequestBody Long[] ids) {
        certificateRenewalInfoService.deleteBatch(ids);
        return R.ok();
    }

}
